package com.photo.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photo.system.common.BaseResponse;
import com.photo.system.common.DeleteRequest;
import com.photo.system.common.ErrorCode;
import com.photo.system.common.ResultUtils;
import com.photo.system.exception.BusinessException;
import com.photo.system.exception.ThrowUtils;
import com.photo.system.model.dto.comments.CommentsAddRequest;
import com.photo.system.model.dto.comments.CommentsQueryRequest;
import com.photo.system.model.dto.comments.CommentsUpdateLikeRequest;
import com.photo.system.model.dto.comments.CommentsUpdateRequest;
import com.photo.system.model.dto.user.UserQueryRequest;
import com.photo.system.model.entity.Comments;
import com.photo.system.model.entity.User;
import com.photo.system.model.vo.LoginUserVO;
import com.photo.system.model.vo.ThingsVO;
import com.photo.system.model.vo.UserVO;
import com.photo.system.service.CommentsService;
import com.photo.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 摄影作品评论接口
 *
 * @author xuwenhui
 */
@RestController
@RequestMapping("/comments")
@Slf4j
@Api(tags = {"摄影作品评论接口"})
public class CommentsController {

    @Resource
    private UserService userService;

    @Resource
    private CommentsService commentsService;


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // region 增删改查

    /**
     * 创建摄影作品评论
     *
     * @param commentsAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建摄影作品评论")
    public BaseResponse<Long> addComments(@RequestBody CommentsAddRequest commentsAddRequest, HttpServletRequest request) {
        if (commentsAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comments comments = new Comments();
        BeanUtils.copyProperties(commentsAddRequest, comments);
        User loginUser = userService.getLoginUser(request);
        comments.setUserId(loginUser.getId());
        comments.setLikeCount(0);
        comments.setCommentTime(new Date());
        boolean result = commentsService.save(comments);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(comments.getId());
    }

    /**
     * 删除作品评论
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除作品评论")
    public BaseResponse<Boolean> deleteComments(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = getLoginUser(request).getData().getId();
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", deleteRequest.getId());
        Comments comment = commentsService.getOne(queryWrapper);
        if (!userId.equals(comment.getUserId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限删除");
        }
        boolean result = commentsService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }

    /**
     * 更新作品评论
     *
     * @param commentsUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新作品评论")
    public BaseResponse<Boolean> updateComments(@RequestBody CommentsUpdateRequest commentsUpdateRequest, HttpServletRequest request) {
        if (commentsUpdateRequest == null || commentsUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有这条评论");
        }
        Long userId = getLoginUser(request).getData().getId();
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", commentsUpdateRequest.getId());
        Comments commentOne = commentsService.getOne(queryWrapper);
        Comments comment = new Comments();

        if (!userId.equals(commentOne.getUserId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限更新");
        }
        BeanUtils.copyProperties(commentsUpdateRequest, comment);
        boolean result = commentsService.updateById(comment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "评论更新失败");
        return ResultUtils.success(result);
    }

    /**
     * 根据id获取全部评论列表
     *
     * @param commentsQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "根据id获取全部评论列表")
    public BaseResponse<Page<Comments>> listUserById(@RequestBody CommentsQueryRequest commentsQueryRequest, HttpServletRequest request) {
        Long id = commentsQueryRequest.getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有这条评论");
        }
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("thingId", id);
        queryWrapper.orderByDesc("commentTime");
        long current = commentsQueryRequest.getCurrent() == 0 ? 1 : commentsQueryRequest.getCurrent();
        long size = commentsQueryRequest.getPageSize() == 0 ? 10 : commentsQueryRequest.getPageSize();

        Page<Comments> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<Comments> pageComments = commentsService.page(pageParam, queryWrapper);
        return ResultUtils.success(pageComments);
    }

    /**
     * 获取作品全部点赞数
     *
     * @param commentsQueryRequest
     * @return
     */
    @PostMapping("/get/all/like")
    @ApiOperation(value = "获取作品全部点赞数")
    public BaseResponse<Long> getLike(@RequestBody CommentsQueryRequest commentsQueryRequest) {
        if (commentsQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 限制爬虫
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", commentsQueryRequest.getId());
        Comments comments = commentsService.getOne(queryWrapper);
        if (comments == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "评论不存在");
        }
        long likeCount = comments.getLikeCount();
        return ResultUtils.success(likeCount);
    }

    // endregion

    /**
     * 更新评论点赞数
     *
     * @param request
     * @return
     */
    @PostMapping("/update/like")
    @ApiOperation(value = "更新评论点赞数")
    public BaseResponse<Boolean> updateCommentsLike(@RequestBody CommentsUpdateLikeRequest commentsUpdateLikeRequest, HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        User user = new User();
        user.setId(loginUser.getId());
        Comments comments = new Comments();
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("thingId", commentsUpdateLikeRequest.getThingId());
        Integer likeCount = commentsUpdateLikeRequest.getLikeCount();
        comments.setLikeCount(likeCount++);
        boolean result = commentsService.updateById(comments);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "评论点赞数更新失败");
        return ResultUtils.success(result);
    }
}
